<?php
/**
* @filename source_module.php 2013-11-11 02:10:56x
* @author Huming Xu <huming17@126.com>
* @version 1.0.0
* @copyright DZF (c) 2013, Huming Xu
*/

class ctrl_area_main extends area_main{
    public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
    
    static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
    /*
	*	取出一条信息
	*/
	public function do_detail($am_id='') {
		$detail = array();
        $am_id = isset($_REQUEST['am_id']) ? $_REQUEST['am_id'] : '';
		$detail = $this->one_info('area_main','am_id',$am_id);
        //DEBUG 调试输出
        include template('area/main/detail');
	}
    
	/*
	*  添加系统信息
	*/
	public function do_add() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$area_main = isset($_REQUEST['area_main']) && !empty($_REQUEST['area_main']) ? $_REQUEST['area_main']:'';
		if('1'==$issubmit){
            //TODO 后端字段校验 根据具体业务逻辑添加
            //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
            foreach($area_main AS $key => $value){
                if(is_array($value) && !empty($value)){
                    $area_main[$key] = implode(",", $value);
                }
            }
            $area_main['create_dateline'] = TIMESTAMP;
            $insert_id = $this->add('area_main',$area_main);
            if($insert_id){
                showmessage('操作成功','index.php?mod=area&action=main&do=index');
            }else{
                showmessage('操作失败','index.php?mod=area&action=main&do=index');
            }
		}else{
			include template('area/main/add');
		}
	}
    
	/*
	*  编辑系统信息
	*/
	public function do_edit() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$area_main = isset($_REQUEST['area_main']) && !empty($_REQUEST['area_main']) ? $_REQUEST['area_main']:'';
        $am_id = isset($_REQUEST['am_id']) ? $_REQUEST['am_id'] : '';
        if($am_id){
            if('1'==$issubmit){
                $area_main['modify_dateline'] = TIMESTAMP;
                //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
                foreach($area_main AS $key => $value){
                    if(is_array($value) && !empty($value)){
                        $area_main[$key] = implode(",", $value);
                    }
                }                
                $where = array('am_id'=>$am_id);
                $effect_row = $this->edit('area_main',$area_main,$where);
                if($effect_row){
                    showmessage('操作成功','index.php?mod=area&action=main&do=index');
                }else{
                    showmessage('操作失败','index.php?mod=area&action=main&do=index');
                }
            }else{
                //DEBUG 获取操作对象信息
                $info = $this->one_info('area_main','am_id',$am_id);
                include template('area/main/edit');
            }
        }else{
            showmessage('请选择编辑对象','index.php?mod=area&action=main&do=index');
        }
	}
    
	/*
	*  删除系统信息
	*/
	public function do_delete() {
        global $_G;
        $am_id = isset($_REQUEST['am_id']) ? $_REQUEST['am_id'] : '';
        if($am_id){
            $effect_row = $this->delete("area_main", array("am_id" => $am_id), $limit=1);
            if($effect_row){
                showmessage('操作成功','index.php?mod=area&action=main&do=index');
            }else{
                showmessage('操作失败','index.php?mod=area&action=main&do=index');
            }
        }
    }
    
	/*
	*  系统信息列表
	*/
	public function do_index() {
        global $_G;
		$area_main_index=$area_main = array();
        //DEBUG 取出所有地区
        $area_main = DB::fetch_all("SELECT am_id,am_name,am_parent_id,am_level FROM ".DB::table('area_main')." WHERE isdelete=0");
        //DEBUG 调试输出
        foreach($area_main AS $key => $value){
            $tmp_value['k'] = $value['am_id'];
            $tmp_value['p'] = $value['am_parent_id'];
            $tmp_value['v'] = $value['am_name'];
            $area_main_index[$key]=$tmp_value;
        }
        //DEBUG 格式化树形数组
        $area_main_index=$this->arr2tree($area_main_index);
        
        if($_G['gp_api']){
            $return['code'] = '0';
            //$return['data']=TIMESTAMP;
            $return['data'][$_G['gp_mod'].'_'.$_G['gp_action'].'_'.$_G['gp_do']]=$area_main_index;
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }
	}
    
	/*
	*  系统信息列表
	*/
	public function do_address() {
        global $_G;
		$area_main_index=$area_main = array();
        //DEBUG 取出所有地区
        $area_main = DB::fetch_all("SELECT am_id,am_name,am_parent_id,am_level FROM ".DB::table('area_main')." WHERE isdelete=0 LIMIT 5000");
        //DEBUG 调试输出
        foreach($area_main AS $key => $value){
            $tmp_value['value'] = $value['am_id'];
            $tmp_value['p'] = $value['am_parent_id'];
            $tmp_value['label'] = $value['am_name'];
            $area_main_index[$key]=$tmp_value;
        }
        //DEBUG 格式化树形数组
        $area_main_index=$this->arr2tree_pc($area_main_index);
        if($_G['gp_api']){
            $return['code'] = '0';
            $return['data']=TIMESTAMP;
            $return['data']=$area_main_index;
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }
	}
    
    /*
     * 后台信息分类数据数组树格式化函数
     * @pram 一维 array $array
     * @return 一维 $array tree
     */
	public function arr2tree($tree, $rootId = 0) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['p'] == $rootId) {
                foreach($tree as $subleaf) {
                    if($subleaf['p'] == $leaf['k']) {
                        $leaf['s'] = $this->arr2tree($tree, $leaf['k']);
                        break;
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }
    
    /*
     * 后台信息分类数据数组树格式化函数
     * @pram 一维 array $array
     * @return 一维 $array tree
     */
	public function arr2tree_pc($tree, $rootId = 0) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['p'] == $rootId) {
                foreach($tree as $subleaf) {
                    if($subleaf['p'] == $leaf['value']) {
                        $leaf['children'] = $this->arr2tree_pc($tree, $leaf['value']);
                        break;
                    }
                }
                unset($leaf['p']);
                $return[] = $leaf;
            }
        }
        return $return;
    }
    
   /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $return_type string json/xml.
     *
     * @return print string json/xml.
     */
	public function do_api(){
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start=(($page-1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if($keyword){
            $wheresql = " WHERE title LIKE '%".$keyword."%'";
        }
        $orderby = " ORDER BY am_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $total_rows,
            //array 一页数据数组
            'page_data' => $page_data 
        );
        */
        $page_result = $this->api('area_main',$page_condition);      
        if('json'==$return_type){
            $return = json_encode($page_result);	
        }elseif('xml'==$return_type){
            $return = array2xml($page_result);
        }
        //DEBUG 接口响应直接输出返回
		echo $return;
	}
    
    /*
	*	取出一条信息
	*/
	public function do_area_school() {
        global $_G;
		$area_main = array();
        //DEBUG 取出所有地区
        $area_main = DB::fetch_all("SELECT am_id,am_name,am_parent_id,am_level FROM ".DB::table('area_main')." WHERE isdelete=0");
        //DEBUG 取出所有学校
        $school_main = DB::fetch_all("SELECT sm_id,sm_type,sm_name,sm_grade,am_id_1,am_id_2,am_id_3 FROM ".DB::table('school_main')." WHERE isdelete=0");
        foreach($school_main AS $key => $value){
            //DEBUG 挂载学校年级班级
            if($value['sm_grade']){
                $sm_grade=explode(',',$value['sm_grade']);
                $value['sm_grade']=array();
                foreach($sm_grade AS $k=>$v){
                    $tmp['grade_num']= $v;
                    $tmp['grade_class']=array();
                    for($i=1; $i < 31; $i++){
                       $tmp['grade_class'][] = array(
                           'class_num'=>$i,
                           'class_name'=>$i.'班'
                       );
                    }
                    $value['sm_grade'][]=$tmp;
                }
            }
            $school_main_area[$value['sm_type']][$value['am_id_3']][]=$value;
        }
        //TODO 从数据库或缓存文件中获取 基本学段年级
        $sm_type = array(1=>"小学",2=>'初中',3=>"高中");
        $grade_array = array(
            '1'=>'一年级',
            '2'=>'二年级',
            '3'=>'三年级',
            '4'=>'四年级',
            '5'=>'五年级',
            '6'=>'六年级',
            '7'=>'初一',
            '8'=>'初二',
            '9'=>'初三',
            '11'=>'高一',
            '12'=>'高二',
            '13'=>'高三'
        );
        $area_school = array();
        foreach($sm_type AS $key => $value){
            $tmp1['sm_type']=$key;
            $tmp1['sm_type_name']=$value;
            $area_main_tmp = array();
            $area_main_tmp = $area_main;
            $tmp_school_main = array();
            foreach($area_main_tmp AS $k=>$v){
                //DEBUG 学校必须在县级下
                if($v['am_level']==3){
                    if(empty($school_main_area[$key][$v['am_id']])){
                        $area_main_tmp[$k]['school_main']=array();
                    }else{
                        $area_main_tmp[$k]['school_main']=$school_main_area[$key][$v['am_id']];
                    }
                }
            }
            $area_main_tmp = $this->dbarr2tree($area_main_tmp);
            $tmp1['sm_type_area']=$area_main_tmp;
            $area_school[]=$tmp1;
        }
        //DEBUG 调试输出
        if($_G['gp_api'] && $_G['check_appsecret']){
            $return = array('code'=>'0');
            if($area_school){
                $return['data']['area_school']=$area_school;
            }
            $return['data']['timestamp']=TIMESTAMP;
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }
	}
    
    /*
     * 后台信息分类数据数组树格式化函数
     * @pram 一维 array $array
     * @return 一维 $array tree
     */
    private function dbarr2tree($tree, $root = 0) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['am_parent_id'] == $root) {
                foreach($tree as $subleaf) {
                    if($subleaf['am_parent_id'] == $leaf['am_id']) {
                        $leaf['children'] = $this->dbarr2tree($tree, $leaf['am_id']);
                        break;
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }
}
?>